package com.tzz.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.tzz.config.PreUrlConfig;
import com.tzz.dao.ActivityOrderDao;
import com.tzz.dao.PreActivityDao;
import com.tzz.dao.ProductDao;
import com.tzz.dao.StationDao;
import com.tzz.entity.ActivityOrder;
import com.tzz.entity.PreActivity;
import com.tzz.exception.PreException;
import com.tzz.service.OrderService;
import com.tzz.utils.ModelDataUtil;
import com.tzz.utils.RandomUtil;
import com.tzz.vo.CreatePreOrderVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    PreActivityDao preActivityDao;

    @Autowired
    StationDao stationDao;

    @Autowired
    ProductDao productDao;

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    ActivityOrderDao activityOrderDao;

    @Resource(name = "preUrlConfig")
    PreUrlConfig preUrlConfig;

    @Override
    @Transactional(rollbackFor=Exception.class)
    public void createOrder(CreatePreOrderVo createPreOrderVo) throws PreException {
        //1、判断站点是否参与了活动
//        2、站点参与的活动是否截单
        List<Integer> stationIdsValid = preActivityDao.getStationIdsById(createPreOrderVo.getPresaleId());
        if(!stationIdsValid.contains(createPreOrderVo.getStationId())){
           throw new PreException("该站点没有参与活动或者活动已经截单") ;
        }
//        3、商品是否在活动中
        List<Integer> skuIds = preActivityDao.getSkuIdsById(createPreOrderVo.getPresaleId());
        for (int i = 0; i <createPreOrderVo.getProducts().size() ; i++) {
            if (!skuIds.contains(createPreOrderVo.getProducts().get(i))){
                throw new PreException("商品 "+createPreOrderVo.getProducts().get(i)+ " 没有参与活动");
            }
        }
        PreActivity preActivity = preActivityDao.getActivityById(createPreOrderVo.getPresaleId());
        //        判断履约时间是否在预售活动时间区间内
        if((createPreOrderVo.getReservedTimeStart().getTime() > preActivity.getDeliveryStartDate().
                getTime()&&(createPreOrderVo.getReservedTimeEnd().
                getTime()<preActivity.getDeliveryEndDate().getTime()))){
            //        4、创建订单
//            JSONObject createOrderModel = ModelDataUtil.getRequestDataModel("create_order");
            JSONObject createOrderModel = getCreateOrderModel(createPreOrderVo);
//            System.out.println(createOrderModel);
            ResponseEntity responseEntity = createOrder(createOrderModel);
//            更新本地数据库
            ActivityOrder activityOrder = new ActivityOrder();
            activityOrder.setActivityId(createPreOrderVo.getPresaleId());
            activityOrder.setOrderId(String.valueOf(createOrderModel.get("orderId")));
            activityOrder.setDeliveryStartTime(createPreOrderVo.getReservedTimeStart());
            activityOrder.setDeliveryEndTime(createPreOrderVo.getReservedTimeEnd());
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String currentDateTime = dateFormat.format(new Date(System.currentTimeMillis()));
            activityOrder.setCreateTime(currentDateTime);
            activityOrder.setBizSubType(createPreOrderVo.getBizSubType());
            activityOrderDao.insertActivityOrder(activityOrder);
        }else {
            throw new PreException("履约时间不在预售活动时间范围内");
        }
    }

    @Override
    public List<ActivityOrder> findActivityOrdersByActivityId(String activityId) {
        return activityOrderDao.getActivityOrderByActivityId(activityId);
    }

    /**
     * 调用ofc接口
     * */
    private ResponseEntity createOrder(JSONObject createOrderModel){
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<JSONObject> httpEntity = new HttpEntity<>(createOrderModel, httpHeaders);
//        String postUrl = preUrlConfig.getUrlMap().get("ofcCreateOrder");
        return restTemplate.postForEntity(preUrlConfig.getUrlMap().get("ofcCreateOrderUrl"), httpEntity, JSONObject.class);
    }

    /**
     * 获取创建接口的请求数据
     * */
    private JSONObject getCreateOrderModel(CreatePreOrderVo createPreOrderVo){
        JSONObject createOrderModel = ModelDataUtil.getRequestDataModel("create_order");
//            改变请求模板信息
        String stationMongo = stationDao.getSingleStationMongoById(createPreOrderVo.getStationId());
        createOrderModel.put("outerStationId",stationMongo);
        createOrderModel.put("saleStationMongoId",stationMongo);
        String orderId = RandomUtil.getOrderId();
        createOrderModel.put("orderId",orderId);
        String start_time = String.valueOf(createPreOrderVo.getReservedTimeStart().getTime()/1000);
        String end_time = String.valueOf(createPreOrderVo.getReservedTimeEnd().getTime()/1000);
        createOrderModel.put("reservedTimeStart",start_time);
        createOrderModel.put("reservedTimeEnd",end_time);
        createOrderModel.put("userReservedTimeStart",start_time);
        createOrderModel.put("userReservedTimeEnd",end_time);
        createOrderModel.put("bizSubType",createPreOrderVo.getBizSubType());
        ArrayList<Object> goodList = new ArrayList<>();
        createOrderModel.put("goods",goodList);
        for (int i = 0; i < createPreOrderVo.getProducts().size(); i++) {
            Map<String, Object> goodModel = getGoodModel();
            String productMongo = productDao.getSingleProductMongoBySkuId(createPreOrderVo.getProducts().get(i));
            goodModel.put("id",productMongo);
            goodModel.put("skuId",productMongo);
            goodModel.put("relationId",productMongo);
            goodModel.put("presaleId",createPreOrderVo.getPresaleId());
            goodList.add(goodModel);
        }
        return createOrderModel;
    }

    /**
     * 获取请求数据good模板
     * */
    private Map<String,Object> getGoodModel(){
        ArrayList<Object> ofSizes = new ArrayList<>();
        ArrayList<Object> accessoryDtoList = new ArrayList<>();
        HashMap<String, Object> good = new HashMap<>();
        good.put("id","61b2bb517b37048ddca85d32");
        good.put("skuId","61b2bb517b37048ddca85d32");
        good.put("type",1);
        good.put("productName","TZZzcy1 180gx1");
        good.put("barCode","");
        good.put("fullName","TZZzcy1 180g");
        good.put("count",5);
        good.put("todayLot",0);
        good.put("relationId","61b2bb517b37048ddca85d32");
        good.put("skuLot","");
        good.put("imageUrl","https://imgnew.ddimg.mobi/product/fc04af6e30824db4be859061e7a704fc.jpg?width=800&amp;height=800");
        good.put("weight",180);
        good.put("price",36);
        good.put("totalPrice",36);
        good.put("originPrice",36);
        good.put("fishery",0);
        good.put("ofcSizes",ofSizes);
        good.put("batchType",-1);
        good.put("batchTodayLet",0);
        good.put("detailSeqNo",0);
        good.put("suggestLotStart","");
        good.put("suggestLotEnd","");
        good.put("parentDetailSeqNoType",0);
        good.put("parentDetailSeqNo",null);
        good.put("operateType",null);
        good.put("presaleId","activity202220221215007");
        good.put("accessoryDtoList",accessoryDtoList);
        return good;
    }
}
